#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' main entry '
__author__ = 'pingwu you'

def read_help():
    import os
    try:
        print(__file__)
        #默认以文本文件模式打开（即字符模式），最好指定编码方式
        f=open(__file__,"r",encoding="utf-8")
        #一次性完全读取文件内容
        str=f.read()
        print(str)
        #一次性完全读取文件内容后返回以行分割的list
        strlist=f.readlines()
        #流打开后只能读取一次，所以返回空
        print(strlist)
    except BaseException as e:
        print(e)
    finally:
        if f:
            f.close()

    with open(__file__,"r",encoding="utf-8") as f:
        strlist=f.readlines()
        print(strlist)
    
    #二进制读取文件内容，返回字节数组
    with open(__file__,"rb") as f:
        bytes=f.read()
        print(bytes)

    with open(__file__,"r",encoding="utf-8") as f:
        slice=10
        tstr=""
        while True:            
            str=f.read(100)
            print("读取一批....")
            if(not str):
                break
            tstr+=str
        print(tstr)

    #覆盖模式
    # with open('/Users/michael/test.txt', 'w',encoding="utf-8") as f:
    # f.write('Hello, world!')
    #追加模式
    # with open('/Users/michael/test.txt', 'a',encoding="utf-8") as f:
    #     f.write('Hello, world!')
    #二进制模式
    # with open('/Users/michael/test.txt', 'wb') as f:
    # f.write(b'Hello, world!')
    # f.write('宗教改革!'.encode("utf-8"))

def stringio_help():
    from io import StringIO
    f=StringIO()
    f.write("中国人民")
    f.write("万岁")
    print(f.getvalue())

    f=StringIO("中级会计看了看")
    print(f.read())

def byteio_help():
    from io import BytesIO
    f=BytesIO()
    f.write("中国人民".encode("utf-8"))
    f.write("万岁".encode("utf-8"))
    print(f.getvalue().decode("utf-8"))

    f=BytesIO("中级会计看了看".encode("utf-8"))
    print(f.read().decode("utf-8"))

def os_help():
    import os
    #当前目录是shell会话环境下的当前目录
    #pwd>>>c:\ab\cd\python.exe d:\xx\yy\zz\main.py
    #当前目录.还是pwd
    root=os.path.abspath('.')
    print(root)
    #可以正确处理不同操作系统的路径分隔符
    dir=os.path.join(root, 'testdir')
    print(dir)
    os.mkdir(dir)
    os.rmdir(dir)

#只能在python 内部且同一版本才有效
def pikle_help():
    import pickle
    dic={"name":"长官课件课件","kk":"课件课件"}
    from io import BytesIO
    f=BytesIO()
    pickle.dump(dic,f)
    print(f.getvalue())
    f2=BytesIO(f.getvalue())
    dic111=pickle.load(f2)
    print(dic111)

#由于JSON标准规定JSON编码是UTF-8，所以我们总是能正确地在Python的str与JSON的字符串之间转换。
def json_help():
    import json
    dic={"name":"长官课件课件","kk":"课件课件"}
    js=json.dumps(dic)
    print(js)
    dic2=json.loads(js)
    print(dic2)

    class Student():
        def __init__(self,name,school) -> None:
            self.name=name
            self.school=school
        def __str__(self):
            return "name:%s,school:%s"%(self.name,self.school)
    
    st=Student("张","一中")
    #默认情况下，dumps()方法不知道如何将Student实例变为一个JSON的{}对象。
    #可选参数default就是把任意一个对象变成一个可序列为JSON的对象
    js2=json.dumps(st,default=lambda obj:obj.__dict__)
    print(js2)
    #反序列化时，再基于dict构建student
    st2=json.loads(js2,object_hook=lambda dict:Student(dict["name"],dict["school"]))
    print(st2)

